package com.zhengke.controller.xwgl;


import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zhengke.common.util.*;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.zhengke.common.object.AjaxDone;
import com.zhengke.common.object.Result;
import com.zhengke.pojo.JournalismPhone;
import com.zhengke.service.xwgl.XWGLService;

@Controller
@RequestMapping("xw")
public class XWGLController {
    @Autowired
    private XWGLService service;

    /**
     * 跳转到展示新闻页面
     *
     * @return
     */
    @RequestMapping("toXW001.do")
    public String toXW001() {
        return "xwgl/toxwgl";
    }

    /**
     * 新闻集合
     *
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping("list.do")
    @ResponseBody
    public Result list(int page, int limit) {
        Result rs = service.queryXW(page, limit);
        return rs;
    }

    /**
     * 跳转到添加新闻界面
     *
     * @return
     */
    @RequestMapping("addXW.do")
    public String addXW() {
        return "xwgl/XW002";
    }

    @ResponseBody
    @RequestMapping("addxw.do")
    public AjaxDone addxw(HttpServletRequest request, HttpServletResponse response) {
        String title = request.getParameter("title");
        String gcPicpath = request.getParameter("gcPicpath");
        String content = request.getParameter("content");
        JournalismPhone jp = new JournalismPhone();
        jp.setTitle(title);
        jp.setTitleImg(gcPicpath);
        jp.setContent(content);
        jp.setCreateTime(new SimpleDateFormat().format(new Date()));
        //根据session中保存的信息获取创建者id
        jp.setCreateUser("1");
        service.addxw(jp);
        return new AjaxDone("200", "保存成功！");
    }

    /**
     * 删除新闻
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping("delxw.do")
    public AjaxDone delxw(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        return service.delxw(id);
    }

    /**
     * 去新闻修改页面
     *
     * @param picPath
     * @param request
     * @param model
     * @return
     */

    @RequestMapping("toXW003.do")
    public String toXWOO3(String picPath, HttpServletRequest request, ModelMap model) {
        try {
            if (picPath == null || "".equals(picPath)) {
                model.put("picPath", request.getSession().getServletContext().getRealPath("/images/") + "/nopic.png");
            } else {
                model.put("picPath", picPath);
            }
            String imgW = LoadProperties.findValue("imgW");
            String imgH = LoadProperties.findValue("imgH");
            model.put("imgW", imgW);
            model.put("imgH", imgH);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "xwgl/XW003";
    }

    /**
     * 修改新闻
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping("updxw.do")
    public AjaxDone updxw(HttpServletRequest request, HttpServletResponse response) {
        String fileServerUrl = null;
        try {
            fileServerUrl = LoadProperties.findValue("FILE_SERVER_URL");
        } catch (IOException e) {
            e.printStackTrace();
        }
        String id = request.getParameter("id");
        String title = request.getParameter("title");
        String titleImg = request.getParameter("gcPicpath").replace(fileServerUrl, "");
        //System.err.println("-==-=-=-=-=-=-=-" + titleImg);
        String content = request.getParameter("content");
        String fileId = request.getParameter("fileId");
        JournalismPhone jp = new JournalismPhone();
        jp.setId(Integer.valueOf(id));
        jp.setTitle(title);
        jp.setTitleImg(titleImg);
        jp.setContent(content);
        //删除以前上传的图片
        int s = service.updxw(jp);
        fileId = fileId.replace(fileServerUrl, "");
        if (s > 0) {
            if (!titleImg.equals(fileId)) {
                FastDfsApiOpr.deleteFile(fileId);
            }
            return new AjaxDone("200", "success");
        }
        return new AjaxDone("300", "系统异常！");
    }

    /**
     * 上传原始图片
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("uploadImage.do")
    public AjaxDone updateImage(@RequestParam(value = "images", required = false) CommonsMultipartFile images) {
        try {
            String imageFileName = images.getOriginalFilename();

            if (imageFileName.indexOf(".jpg") == -1
                    && imageFileName.indexOf(".gif") == -1
                    && imageFileName.indexOf(".png") == -1
                    && imageFileName.indexOf(".jpeg") == -1) {
                return new AjaxDone("300", "文件格式不正确，请上传 *.png,*.jpeg,*.gif,*.jpg类型图片");
            }

            String extName = imageFileName.substring(imageFileName.lastIndexOf(".") + 1);
            if (images != null && !images.isEmpty()) {
                String path = LoadProperties.findValue("imgPath") + "/" + DateUtil.getSystemDateTimeByFormat("yyyyMMddHHmmss") + "." + extName;
                File file = new File(path);
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                FileUtils.copyInputStreamToFile(images.getInputStream(), file);
                String rtnPath = LoadProperties.findValue("viewUrl") + "?path=" + file.getPath();

                return new AjaxDone("200", "上传成功", rtnPath, path);
            } else {
                return new AjaxDone("300", "文件格式不正确，请上传 *.png,*.jpeg,*.gif,*.jpg类型图片");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxDone("300", "上传失败");
    }

    /**
     * 上传剪切后的图片
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("uploadCanvas.do")
    public AjaxDone updateConvars(String gcId, String canvasData, String delFile) {
        try {
            String path = LoadProperties.findValue("imgPath") + "/";
            String fileName = DateUtil.getSystemDateTimeByFormat("yyyyMMddHHmmss") + ".jpg";

            File file = Base64ToImage.decodeBase64ToImage(canvasData, path, fileName);

            //删除原图片
            File delete = new File(delFile);
            if (delete != null) {
                delete.delete();
            }

            if (file != null) {
                String imgW = LoadProperties.findValue("imgW");
                String imgH = LoadProperties.findValue("imgH");
                //保存canvas转成的缩略图
                String filePath = ImageUtil.thumbnailImage(file.getPath(), Integer.parseInt(imgW), Integer.parseInt(imgH), true);
                //删除canvas原图
                file.delete();

                /*
                fastDFS操作
                 */
                //获取文件的扩展名
                String filename = fileName;
                //获取文件后缀名 从最后一个点后一位截取
                String extName = fileName.substring(filename.lastIndexOf(".") + 1);
                //上传fastDFS后图片完整地址
                String file_id = FastDfsApiOpr.upload(filePath, extName);
                //读取config.properties查找访问路径的ip+端口
                String rtnPath = LoadProperties.findValue("FILE_SERVER_URL") + file_id;
				/*System.out.println(file_id);
				System.out.println(rtnPath);*/
                //删除剪切后的本地图片
                File delCanvas = new File(filePath);
                if (delCanvas != null) {
                    delCanvas.delete();
                }
                return new AjaxDone("200", "上传成功!", rtnPath, file_id);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxDone("300", "系统繁忙,请稍后重试!");
    }
}
